package solution;

/**
 * <a href="https://www.nowcoder.com/practice/5d3d74c3bf7f4e368e03096bb8857871?tpId=188&&tqId=38592&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking">
 * NC156 数组中只出现一次的数</a>
 *
 * @author or2
 * @date 2021/8/1 14:55
 */
public class FoundOnceNumber {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param arr int一维数组
     * @param k   int
     * @return int
     */
    public int foundOnceNumber(int[] arr, int k) {
        if (k % 2 == 0) {
            int sum = 0;
            for (int i : arr) {
                sum ^= i;
            }
            return sum;
        } else {
            int[] bits = new int[32];
            for (int i : arr) {
                for (int bit = 0; bit < bits.length; bit++) {
                    bits[bit] += (i & (1 << bit)) >> bit;
                }
            }

            int ans = 0;
            for (int i = 0; i < bits.length; i++) {
                ans |= bits[i] % k << i;
            }

            return ans;
        }
    }
}
